package com.sx.rabbitmqtest.mq;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class DelayMessageSender implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {
    private RabbitTemplate rabbitTemplate;

    @Autowired
    public DelayMessageSender(RabbitTemplate rabbitTemplate){
        this.rabbitTemplate = rabbitTemplate;
        rabbitTemplate.setReturnCallback(this);
        rabbitTemplate.setConfirmCallback(this);
    }

    public void sendMsg(String msg, CorrelationData correlationData){
        System.out.println("send msg: " + msg + " with id:" + correlationData.getId());
        rabbitTemplate.convertAndSend(RabbitMQConfig.RABBIT_EXCHANGE_TTL, RabbitMQConfig.TTL_ROUTING_KEY, msg, correlationData);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if(ack) {
            System.out.println("id: " + correlationData.getId() + " is send to mq success!");
        }else{
            System.out.println("[error] id: " + correlationData.getId() + " is send to mq fail!");
        }
    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        System.out.println("id: " + message.getMessageProperties().getCorrelationId() + "is return! code:" + replyCode);
    }
}
